package y_2025.m11.d05;

public class BankAccountUnsafe {
    private int balance = 100; // 初始余额100元
    
    // 不安全的存款方法
    public void deposit(int amount) {
        int current = balance;           // 步骤1：读取当前余额
        int newBalance = current + amount; // 步骤2：计算新余额
        balance = newBalance;            // 步骤3：写入新余额
    }
    
    public int getBalance() {
        return balance;
    }
    
    public static void main(String[] args) throws InterruptedException {
        BankAccountUnsafe account = new BankAccountUnsafe();
        
        // 创建10个线程，每个线程存10元钱
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(() -> {
                account.deposit(10);
            });
        }
        
        // 启动所有线程
        for (Thread t : threads) {
            t.start();
        }
        
        // 等待所有线程完成
        for (Thread t : threads) {
            t.join();
        }
        
        System.out.println("最终余额: " + account.getBalance());
        // 应该输出200元(100 + 10*10)，但可能输出错误结果
    }
}